package org.ssssssss.magicboot.utils;

import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.util.DigestUtils;

import java.util.LinkedHashMap;
import java.util.Map;

public class SignUtils {

    public static String sign(Map<String,String> map, String key) {
        Map<String, String> newMap = sortByKey(map);
        String signStr = "";
        //遍历map 转成字符串
        for (Map.Entry<String, String> m : newMap.entrySet()) {
            signStr += m.getKey() + "=" + m.getValue() + "&";
        }
        //去掉最后一个 &
        signStr = signStr.substring(0, signStr.length() - 1);
        System.out.println("signStr"+signStr);
        //最后拼接上KEY
        signStr += key;
        //转为MD5
        signStr = DigestUtils.md5DigestAsHex(signStr.getBytes());
        return signStr;
    }

    public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Map.Entry.<K, V>comparingByKey()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        return result;
    }

    public static String sign2(Map<String,String> map, String key) {
        Map<String, String> newMap = sortByKey(map);
        String signStr = "";
        //遍历map 转成字符串
        for (Map.Entry<String, String> m : newMap.entrySet()) {
            signStr += m.getKey() + "=" + m.getValue() + "&";
        }
        //去掉最后一个 &
        signStr = signStr.substring(0, signStr.length() - 1);
        System.out.println("signStr"+signStr);
        //最后拼接上KEY
        signStr += key;
        //转为MD5
        signStr =  DigestUtil.md5Hex(signStr.getBytes());
        return signStr;
    }


}
